package com.menu.controller;

import com.menu.result.Result;
import com.menu.result.ResultFactory;
import com.menu.service.UserService;
import com.menu.utils.RandomUtil;
import com.menu.utils.SendSmsUtil;
import com.menu.redis.StringRedisServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * author: MaHX
 * date: 2019/8/10/2:27
 * description:
 **/
@RestController
public class GetPhoneCodeController {
    @Autowired
    StringRedisServiceImpl stringRedisService;
    @Autowired
    UserService userService;

    @PostMapping("getCode")
    public Result getCode(@RequestParam("phone") String phone, @RequestParam("type") String type) {
        if (userService.findUserByPhone(phone) != null) {
            return ResultFactory.buildFailResult("该号码已注册,请前往登录");
        } else {
            String trueCode = RandomUtil.randomBuilder(4);
            if (type.equals("login")) {
                type = "SMS_172206913";
            } else if (type.equals("reset")) {
                type = "SMS_172222062";
            } else if (type.equals("register")) {
                type = "SMS_172356046";
            }
            stringRedisService.set(phone, trueCode);
            stringRedisService.expire(phone, 300);
            try {
                SendSmsUtil.sendSms(phone, type, trueCode);
            } catch (Exception e) {
                return ResultFactory.buildFailResult("发送失败:" + e.toString());
            }
            return ResultFactory.buildSuccessResult(null);
        }
    }

}
